var websocket = null;
if ("WebSocket" in window) {
  //用于创建WebSocket对象，webSocketTest对应的是java类的注解值。
  websocket = new WebSocket("ws://192.168.0.182:8080/websocket/1");
} else {
  alert("当前浏览器不支持");
}
//        连接发生错误的时候回调方法；
websocket.onerror = function () {
  alert("连接错误");
};
//       连接成功时建立回调方法
websocket.onopen = function () {
  //WebSocket已连接上，使用send()方法发送数据
  // alert("连接成功");
  websocket.readystatechange = function () {
    send("发送数据");
  };
};
//      收到消息的回调方法
websocket.onmessage = function (msg) {
  // alert(JSON.stringify(msg));
  // console.log(msg.data);
  if (isValidJson(msg.data)) {
    var isFind = false;
    let data = JSON.parse(msg.data);
    if (data["type"] == "move") {
      let tank = all_tank.find((element) => {
        if (data["id"] == element.id) {
          element.tank_pointer[0] = data["x"];
          element.tank_pointer[1] = data["y"];
          isFind = true;
          return true;
        }
      });
      // console.log(tank);
    } else if (data["type"] == "gun") {
      // all_tank.forEach((element) => {
      //   if (data["id"] == element.id) {
      //     element.updateTankGunRotate([data["x"], data["y"]]);
      //     // element.target_pointer[0] = data["x"];
      //     // element.target_pointer[1] = data["y"];
      //     isFind = true;
      //   }
      // });
      let index = all_tank.findIndex((element) => {
        if (data["id"] == element.id) {
          element.updateTankGunRotate([data["x"], data["y"]]);
          // element.target_pointer[0] = data["x"];
          // element.target_pointer[1] = data["y"];
          isFind = true;
          return true;
        }
      });
      // console.log(index);
    }
    if (!isFind) {
      const player_tank1 = new CreateTank(
        canvas,
        ctx,
        1,
        3,
        "#c7823d",
        [data["x"], data["y"]],
        data["id"]
      );
      all_tank.push(player_tank1);
      players_tank.push(player_tank1);
    } else {
    }
  }
};
//连接关闭的回调方法
websocket.onclose = function () {
  closed();
  // alert("关闭成功");
};

function closed() {
  websocket.close();
  // alert("点击关闭");
}

function send(message) {
  if (websocket.readyState == WebSocket.OPEN) {
    websocket.send(message); //给后台发送数据
  }
}

function isValidJson(str) {
  const pattern = /^({[^}]*})*$/;
  return pattern.test(str);
}
